package com.appkubes.fintech.restful.application.file.service.impl;


import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.fintech.restful.application.file.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

@Service("LocalFileServiceImpl")
@Slf4j
public class LocalFileServiceImpl implements FileStorageService {

    @Value("${idcard.image.base.path}")
    private String IDCARD_IMAGE_BASE_PATH;


    @Override
    public String upload(MultipartFile file) {
        //替换成自己路径.想要存储文件的地址
        String pathName = this.IDCARD_IMAGE_BASE_PATH;

        String filename = file.getOriginalFilename();
        String exName = FilenameUtils.getExtension(filename);

        String storageName = "/images/" + DateFormatUtils.format(new Date(), "YYYYmmdd") + "/"
                + UUIDUtils.getUUID() + "." + exName;
        pathName += storageName;

        //创建文件夹
        File existFile = new File(pathName);
        if (!existFile.getParentFile().exists()) {
            existFile.getParentFile().mkdirs();
        }

        try (
                FileOutputStream fos = new FileOutputStream(pathName);
        ) {

            // 写入文件
            fos.write(file.getBytes());
            return storageName;

        } catch (Exception e) {
            log.error("文件上传失败", e);
        }
        return null;
    }
}
